{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:19:27.348811Z",
     "start_time": "2025-01-08T07:19:27.128958Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 导入库\n",
    "import pandas as pd\n",
    "import numpy as np"
   ],
   "id": "cfe0b0e67d133176",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# Pandas 索引操作",
   "id": "97bec5836299103f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:20:19.633248Z",
     "start_time": "2025-01-08T07:20:19.629024Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 创建 DataFrame 对象\n",
    "dict_data = {'A': 1,\n",
    "             'B': pd.Timestamp('20190926'),\n",
    "             'C': pd.Series(1, index=list(range(4)), dtype='float32'),\n",
    "             'D': np.array([1, 2, 3, 4], dtype='int32'),\n",
    "             'E': [\"Python\", \"Java\", \"C++\", \"C\"],\n",
    "             'F': 'wangdao'}\n",
    "df_obj2 = pd.DataFrame(dict_data)"
   ],
   "id": "29c6381cb45c0271",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:20:53.012843Z",
     "start_time": "2025-01-08T07:20:53.009739Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 索引对象的值不可变，因此不能修改索引值，只能修改索引名称\n",
    "#df_obj2.index[0] = 2"
   ],
   "id": "5f6bd6114b17b25f",
   "outputs": [],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 常见index类型\n",
    "•Index，索引 可以是各种类型 •Int64Index，整数索引 •MultiIndex，层级索引，难度较大 •DatetimeIndex，时间戳类型"
   ],
   "id": "fd7d36d2b0852dc4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:22:38.017670Z",
     "start_time": "2025-01-08T07:22:38.011284Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# index:设置索引名称\n",
    "ser_obj = pd.Series(range(5), index=list(\"abcde\"))\n",
    "print(ser_obj)\n",
    "ser_obj.index"
   ],
   "id": "8791e0d965c3b630",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:26:34.586724Z",
     "start_time": "2025-01-08T07:26:34.582222Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 行索引，不仅可以用索引名，可以用索引位置取值\n",
    "\n",
    "# .loc[]:通过索引名取值\n",
    "print(ser_obj.loc['a'])\n",
    "\n",
    "# .iloc[]:通过索引位置取值\n",
    "print(ser_obj.iloc[2])"
   ],
   "id": "ffd14a2610ea591f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "\n",
      "\n",
      "2\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:28:51.754462Z",
     "start_time": "2025-01-08T07:28:51.750563Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 切片索引\n",
    "\n",
    "# .loc[]:通过索引名取值,注意左闭右闭\n",
    "print(ser_obj.loc['a':'c'])\n",
    "\n",
    "# .iloc[]:通过索引位置取值,注意左闭右开\n",
    "print(ser_obj.iloc[0:2])"
   ],
   "id": "d18aa94128d1b68e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "a    0\n",
      "b    1\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 30
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:29:34.216058Z",
     "start_time": "2025-01-08T07:29:34.212001Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 不连续索引\n",
    "\n",
    "# .loc[]::通过索引名取值,注意左闭右闭\n",
    "print(ser_obj.loc[['a', 'e']])\n",
    "\n",
    "# .iloc[]:通过索引位置取值,注意左闭右开\n",
    "print(ser_obj.iloc[[0, 2, 4]])"
   ],
   "id": "ec89486dc778f833",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "e    4\n",
      "dtype: int64\n",
      "a    0\n",
      "c    2\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 31
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:31:20.863679Z",
     "start_time": "2025-01-08T07:31:20.859674Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 布尔索引\n",
    "\n",
    "ser_bool = ser_obj > 2\n",
    "\n",
    "#取出大于2的元素\n",
    "print(ser_obj[ser_bool])\n",
    "\n",
    "# 等价于\n",
    "print(ser_obj[ser_obj > 2])"
   ],
   "id": "aa5eb2dc75e0b13d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "execution_count": 33
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 对齐运算",
   "id": "a9ace74ab235fc06"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:47:43.636524Z",
     "start_time": "2025-01-08T07:47:43.630062Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 创建两个 Series 对象\n",
    "s1 = pd.Series(range(10, 20), index=range(10))\n",
    "s2 = pd.Series(range(20, 25), index=range(5))\n",
    "\n",
    "# 对齐运算\n",
    "#缺失数据默认是NaN  np.nan\n",
    "print('s1+s2: ')\n",
    "s3 = s1 + s2\n",
    "print(s3)\n",
    "\n",
    "#未对齐的数据将和填充值做运算\n",
    "# fill_value方法可以指定填充值: fill_value=0\n",
    "print(s2.add(s1, fill_value=0))\n",
    "print(s2.sub(s1, fill_value=0))"
   ],
   "id": "9029c0b0e5fd504c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s1+s2: \n",
      "0    30.0\n",
      "1    32.0\n",
      "2    34.0\n",
      "3    36.0\n",
      "4    38.0\n",
      "5     NaN\n",
      "6     NaN\n",
      "7     NaN\n",
      "8     NaN\n",
      "9     NaN\n",
      "dtype: float64\n",
      "0    30.0\n",
      "1    32.0\n",
      "2    34.0\n",
      "3    36.0\n",
      "4    38.0\n",
      "5    15.0\n",
      "6    16.0\n",
      "7    17.0\n",
      "8    18.0\n",
      "9    19.0\n",
      "dtype: float64\n",
      "0    10.0\n",
      "1    10.0\n",
      "2    10.0\n",
      "3    10.0\n",
      "4    10.0\n",
      "5   -15.0\n",
      "6   -16.0\n",
      "7   -17.0\n",
      "8   -18.0\n",
      "9   -19.0\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 36
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:45:29.384460Z",
     "start_time": "2025-01-08T07:45:29.380463Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#两个长度不同的一维ndarray相加\n",
    "a1 = np.array([1, 2, 3, 4, 5])\n",
    "a2 = np.array([1])\n",
    "\n",
    "# 广播机制\n",
    "print(a2.shape)\n",
    "print(a1 + a2)"
   ],
   "id": "670e79ffd6130202",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1,)\n",
      "[2 3 4 5 6]\n"
     ]
    }
   ],
   "execution_count": 35
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-08T07:48:46.080135Z",
     "start_time": "2025-01-08T07:48:46.071627Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 两个DataFrame的对齐运算\n",
    "\n",
    "# 创建两个 DataFrame 对象\n",
    "df1 = pd.DataFrame(np.ones((2, 2)), columns=['a', 'b'])\n",
    "df2 = pd.DataFrame(np.ones((3, 3)), columns=['a', 'b', 'c'])\n",
    "print(df1)\n",
    "print(df2)\n",
    "\n",
    "# 对齐运算\n",
    "print(df1 - df2)\n",
    "print(df2.sub(df1, fill_value=2))"
   ],
   "id": "5923f09be8524ccf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     a    b\n",
      "0  1.0  1.0\n",
      "1  1.0  1.0\n",
      "     a    b    c\n",
      "0  1.0  1.0  1.0\n",
      "1  1.0  1.0  1.0\n",
      "2  1.0  1.0  1.0\n",
      "     a    b   c\n",
      "0  0.0  0.0 NaN\n",
      "1  0.0  0.0 NaN\n",
      "2  NaN  NaN NaN\n",
      "     a    b    c\n",
      "0  0.0  0.0 -1.0\n",
      "1  0.0  0.0 -1.0\n",
      "2 -1.0 -1.0 -1.0\n"
     ]
    }
   ],
   "execution_count": 37
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "总结：没对齐的元素，默认填充NaN，对齐运算时，fill_value参数可以指定填充值。",
   "id": "e0c5c85af7cf6cfa"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
